package com.example.controller;

import com.example.entity.Teacher;
import com.example.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/teacher")
public class TeacherInfoController {

    @Autowired
    private TeacherService teacherService;

    @GetMapping("/info")
    public String showTeacherInfo(HttpSession session, Model model) {
        // 检查登录状态和用户类型
        if (session.getAttribute("loggedIn") == null || !"teacher".equals(session.getAttribute("userType"))) {
            return "redirect:/index";
        }

        Integer teacherId = (Integer) session.getAttribute("teacherId");
        Teacher teacher = teacherService.getTeacherById(teacherId);
        model.addAttribute("teacher", teacher);
        return "teacher/info";
    }

    @PostMapping("/info/update")
    public String updateTeacherInfo(@ModelAttribute Teacher teacher, HttpSession session) {
        // 检查登录状态和用户类型
        if (session.getAttribute("loggedIn") == null || !"teacher".equals(session.getAttribute("userType"))) {
            return "redirect:/index";
        }

        teacherService.updateTeacherInfo(teacher);
        return "redirect:/teacher/info";
    }

    @PostMapping("/password/update")
    public String updateTeacherPassword(@RequestParam("newPassword") String newPassword, HttpSession session) {
        // 检查登录状态和用户类型
        if (session.getAttribute("loggedIn") == null || !"teacher".equals(session.getAttribute("userType"))) {
            return "redirect:/index";
        }

        Integer teacherId = (Integer) session.getAttribute("teacherId");
        teacherService.updateTeacherPassword(teacherId, newPassword);
        return "redirect:/teacher/info";
    }
}